package com.neusoft.chatserver.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.neusoft.chatserver.dto.RespBean;
import com.neusoft.chatserver.entity.Users;
import com.neusoft.chatserver.mapper.UsersMapper;
import com.neusoft.chatserver.service.IUsersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author liuxp
 * @since 2021-07-14
 */
@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements IUsersService {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public List<Integer> setUserOnline(int userid) {
        ValueOperations<String, Object> stringObjectValueOperations = redisTemplate.opsForValue();
        String s = (String) stringObjectValueOperations.get("OnlineUser");
        List<Integer> list = (List<Integer>) JSONObject.parse(s);
        if (list == null) {
            list = new ArrayList<>();
        }
        if (!list.contains(userid))
            list.add(userid);
        stringObjectValueOperations.set("OnlineUser", JSONObject.toJSONString(list));
        return list;
    }

    @Override
    public List<Integer> setUserOffline(int userid) {
        ValueOperations<String, Object> stringObjectValueOperations = redisTemplate.opsForValue();
        String s = (String) stringObjectValueOperations.get("OnlineUser");
        List<Integer> list = (List<Integer>) JSONObject.parse(s);
        if (list == null) {
            list = new ArrayList<>();
        }
        if (list.contains(userid))
            list.remove(list.indexOf(userid));
        stringObjectValueOperations.set("OnlineUser", JSONObject.toJSONString(list));
        return list;
    }

    @Override
    public List<Integer> getUserOnlineStatus(List<Integer> ids) {
        ValueOperations<String, Object> stringObjectValueOperations = redisTemplate.opsForValue();
        String s = (String) stringObjectValueOperations.get("OnlineUser");
        List<Integer> list = (List<Integer>) JSONObject.parse(s);
        if (list == null) {
            list = new ArrayList<>();
        }
        List<Integer> onlineStatus = new ArrayList<>();
        for (Integer id : ids) {
            if (list.contains(id)) {
                onlineStatus.add(1);
            } else {
                onlineStatus.add(0);
            }
        }
        return onlineStatus;

    }
}
